package homework7_30;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/*
 * ��ҵ1.
����sort.txt
 */
public class java01 {
    public static void main(String[] args) {
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader("sort.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    lines.add(line);
                }
            }
        } catch (IOException e) {
            System.err.println("Error reading the file: " + e.getMessage());
            return;
        }
        Collections.sort(lines, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int num1 = extractNumber(o1);
                int num2 = extractNumber(o2);
                return Integer.compare(num1, num2);
            }
            
            private int extractNumber(String s) {
                String[] parts = s.split("\\.", 2);
                if (parts.length > 0) {
                    try {
                        return Integer.parseInt(parts[0].trim()); // 提取并转换为整数
                    } catch (NumberFormatException e) {
                        return Integer.MAX_VALUE;
                    }
                }
                return Integer.MAX_VALUE;
            }
        });
        for (String line : lines) {
            System.out.println(line);
        }
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("sorted_sort.txt"))) {
            for (String line : lines) {
                writer.write(line + "\n");
            }
        } catch (IOException e) {
            System.err.println("Error writing to file: " + e.getMessage());
        }
    }
}